//
//  setting.m
//  testvideo
//
//  Created by fcbayern on 2021/1/6.
//  Copyright © 2021 fcbayern. All rights reserved.
//

#import "setting.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "mycell.h"
#import "Single.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import <objc/runtime.h>
#import "MJRefresh.h"
@interface setting ()
@property(strong,nonatomic)UILabel * username;
@property(strong,nonatomic)UICollectionView * collection;
@property(strong,nonatomic)UILabel * showcollection;
@property(strong,nonatomic)UIImageView * headerimage;


@end

@implementation setting
-(void)viewDidLoad{
     [super viewDidLoad];
    
    
    NSString * userurl = @"http://106.52.91.37:8081/api/user/self";
    AFHTTPSessionManager * manager3 = [AFHTTPSessionManager manager];
    manager3.responseSerializer = [AFJSONResponseSerializer serializer];
    manager3.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager3 GET:userurl parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * returnjson = responseObject;
        NSString * name = returnjson[@"Data"][@"Info"][@"Name"];
        _username = [[UILabel alloc] init];
           _showcollection = [[UILabel alloc] init];
           _headerimage = [[UIImageView alloc] init];
           [self.view addSubview:_headerimage];
           [self.view addSubview:_username];
           [self.view addSubview:_showcollection];
           UIImage * im = [UIImage imageNamed:@"header"];
           _headerimage.image = im;
           [_headerimage mas_makeConstraints:^(MASConstraintMaker *make) {
               make.top.equalTo(self.view.mas_top).with.offset(110);
               make.left.equalTo(self.view.mas_left).with.offset(50);
               make.width.equalTo(self.view.mas_width).multipliedBy(0.3);
               make.height.equalTo(self.view.mas_width).multipliedBy(0.3);
           }];
           _headerimage.layer.cornerRadius = self.view.frame.size.width*0.3/2;
           _headerimage.backgroundColor = [UIColor whiteColor];
           [_username mas_makeConstraints:^(MASConstraintMaker *make) {
               make.top.equalTo(self.view.mas_top).with.offset(100);
               make.width.equalTo(self.view).multipliedBy(0.4);
               make.right.equalTo(self.view.mas_right).with.offset(-30);
               make.height.equalTo(self.view).multipliedBy(0.1);
           }];
           _username.font = [UIFont fontWithName:@"PingFang SC" size: 45];
           _username.text = name;
           _username.textColor = [UIColor whiteColor];
           
           [_showcollection mas_makeConstraints:^(MASConstraintMaker *make) {
               make.top.equalTo(_username.mas_bottom).with.offset(100);
               make.width.equalTo(self.view).multipliedBy(0.9);
               make.centerX.equalTo(self.view);
               make.height.equalTo(self.view).multipliedBy(0.04);
           }];
           _showcollection.layer.cornerRadius = 10;
           _showcollection.text = @"我的收藏";
           _showcollection.backgroundColor = [UIColor colorWithRed:228/255.0 green:40/255.0 blue:74/255.0 alpha:1];
           UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
           layout.scrollDirection = UICollectionViewScrollDirectionVertical;
           layout.itemSize = CGSizeMake(180, 150);
           _collection = [[UICollectionView alloc]initWithFrame:self.view.frame  collectionViewLayout:layout];
           [_collection registerClass:[mycell class] forCellWithReuseIdentifier:@"cellid"];
           _collection.delegate=self;
           _collection.dataSource=self;
           _collection.backgroundColor = [UIColor whiteColor];
           [self.view addSubview:_collection];
           [_collection mas_makeConstraints:^(MASConstraintMaker *make) {
               make.top.equalTo(_showcollection.mas_bottom).with.offset(20);
               make.bottom.equalTo(self.view.mas_bottom).with.offset(-40);
               make.width.equalTo(self.view.mas_width).multipliedBy(0.9);
               make.centerX.equalTo(self.view);
           }];
           _collection.backgroundColor = [UIColor colorWithRed:50/255.0 green:50/255.0 blue:50/255.0 alpha:1];
           _collection.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    
    

}

-(void)refreshData{
    
  [self viewWillAppear:YES];
 
  [_collection.mj_header endRefreshing];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:50/255.0 green:50/255.0 blue:50/255.0 alpha:1];
    [[Single sharedInstance].collectionlist removeAllObjects];
    
    NSString * url = @"http://106.52.91.37:8081/api/video/getstar";
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    ((AFJSONResponseSerializer *)manager.responseSerializer).removesKeysWithNullValues = YES;
    [manager GET:url parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableArray * returnjson = responseObject[@"Message"];
        for(id key in returnjson){
            [[Single sharedInstance].collectionlist addObject:key];
        }
        [_collection reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
   
    
    
}


#pragma mark <UICollectionViewDataSource>
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView * )collectionView{
    if([Single sharedInstance].collectionlist.count%2 == 0){
        return [Single sharedInstance].collectionlist.count/2;
    }
    else{
        return [Single sharedInstance].collectionlist.count/2+1;
    }
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 2;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    mycell * cell;
    
    if([Single sharedInstance].collectionlist.count > 0){
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
        int pos =indexPath.section*2+indexPath.row;
        if(pos>=[Single sharedInstance].collectionlist.count){
            cell.title.text = @"";
            cell.mainview.image = nil;
            cell.layer.borderWidth = 0;
            cell.contentView.backgroundColor = [UIColor colorWithRed:50/255.0 green:50/255.0 blue:50/255.0 alpha:1];
            [cell.Delete setImage:nil forState:UIControlStateNormal];
        }
        else{
            [cell.title setText:[Single sharedInstance].collectionlist[pos][@"Title"]];
            NSString * fin_url =[[NSString alloc] initWithFormat:@"%@%@",@"http://106.52.91.37:8081/api/video/public/",[Single sharedInstance].collectionlist[pos][@"Image"]];
             UIImage * header = [UIImage imageWithData:[NSData  dataWithContentsOfURL:[NSURL URLWithString:fin_url]]];
            //UIImage * header = [UIImage imageNamed:@"video"];
            cell.mainview.image = header;
            cell.layer.borderColor = [UIColor blackColor].CGColor;
            cell.layer.borderWidth = 2;
            cell.layer.cornerRadius = 20;
            cell.mainview.layer.cornerRadius = 20;
            cell.contentView.backgroundColor = [UIColor whiteColor];
            cell.layer.masksToBounds=YES;
            [cell.Delete setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
            
            [cell.Delete addTarget:self action:@selector(deleteact2:) forControlEvents:UIControlEventTouchUpInside];
        }
        NSMutableDictionary *nsDic2 = [[NSMutableDictionary alloc]init];
        NSInteger section2 = indexPath.section;
        NSInteger row2 = indexPath.row;
        NSNumber *numbersec2 = [NSNumber numberWithInt:section2];
        NSNumber *numberrow2 = [NSNumber numberWithInt:row2];
        [nsDic2 setObject:numbersec2 forKey:@"section"];

        [nsDic2 setObject:numberrow2 forKey:@"row"];
        
        objc_setAssociatedObject(cell.Delete, @"myBtn2", nsDic2, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    else{
        NSLog(@"%@",[Single sharedInstance].collectionlist);
         cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    }
    
    return cell;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{
    return UIEdgeInsetsMake(15,0,15,0);

}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    int section = indexPath.section;
    int row = indexPath.row;
    int pos = indexPath.section*2+indexPath.row;
    if(pos >=[Single sharedInstance].collectionlist.count){
        
    }
    else{
        NSString * tempurl = [[NSString alloc] initWithFormat:@"%@%@",@"http://106.52.91.37:8081/api/video/public/",[Single sharedInstance].collectionlist[pos][@"URL"]];
        NSURL *webVideoUrl = [NSURL URLWithString:tempurl];
           //步骤2：创建AVPlayer
        AVPlayer *avPlayer = [[AVPlayer alloc] initWithURL:webVideoUrl];
           //步骤3：使用AVPlayer创建AVPlayerViewController，并跳转播放界面
        AVPlayerViewController *avPlayerVC =[[AVPlayerViewController alloc] init];
        avPlayerVC.player = avPlayer;
        [avPlayerVC.player play];
        [self presentViewController:avPlayerVC animated:YES completion:nil];
    }

}

-(void)deleteact2:(UIButton*)sender {
    NSDictionary *dic = objc_getAssociatedObject(sender, @"myBtn2");
    int section = [[dic objectForKey:@"section"] intValue];
    int row = [[dic objectForKey:@"row"] intValue];
    if(section*2+row>=[Single sharedInstance].collectionlist.count){
    }
    else{
        
        UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要删除吗?" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert1 animated:YES completion:nil];
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                   NSString * deleteid = [Single sharedInstance].collectionlist[section*2+row][@"Vid"];
                    NSString * deleteurl =[[NSString alloc]initWithFormat:@"%@%@",@"http://106.52.91.37:8081/api/video/delete/",deleteid];
                    AFHTTPSessionManager * manager3 = [AFHTTPSessionManager manager];
                    manager3.responseSerializer = [AFJSONResponseSerializer serializer];
                    manager3.requestSerializer = [AFJSONRequestSerializer serializer];
                    [manager3 DELETE:deleteurl parameters:nil headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        [[Single sharedInstance].collectionlist removeObjectAtIndex:section*2+row];
                        UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"提示" message:@"删除成功" preferredStyle:UIAlertControllerStyleAlert];
                        [self presentViewController:alert1 animated:YES completion:nil];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
                        });
                        [_collection reloadData];
                        
                        
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        
                    }];
            }];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                   
            }];
        [alert1 addAction:defaultAction];
        [alert1 addAction:cancelAction];
        
    }
}

@end
